package cn.kvchoi.reactor_simulation;

import cn.kvchoi.reactor_simulation.handlers.ReadEventHandler;
import cn.kvchoi.reactor_simulation.handlers.WriteEventHandler;

/**
 * Simulation for Reactor Pattern by an Event Drive Model
 */
public class SimulationApp {

    public static void main(String[] args) {
        //init
        final Selector selector = new Selector();
        Dispatcher dispatcher = new Dispatcher(selector);
        dispatcher.registerHandler(EventType.READ, new ReadEventHandler());
        dispatcher.registerHandler(EventType.WRITE, new WriteEventHandler());

        //produce
        for (int i = 0; i < 10; i++) {
            final int j = i;
            Thread t = new Thread(new Runnable() {

                @Override
                public void run() {
                    if (j % 2 == 0) {
                        selector.addEvent(new Event(EventType.READ));
                    } else {
                        selector.addEvent(new Event(EventType.WRITE));
                    }
                }
            });
            t.start();
        }

        //consume
        dispatcher.handle();
    }

}
